<?php

namespace app\merchant\controller;

use app\common\controller\Tools;
use app\common\model\Goods as GoodsModel;
use app\common\model\OrderModel;
use app\common\tool\OSSUtils;
use app\common\tool\SFDeliver;
use think\Request;

use app\common\tool\BSP;

class Book extends Common
{
    protected $book;

    public function _initialize()
    {
        parent::_initialize();
        $this->book = new \app\common\model\Book();
    }

    /**
     * 图书列表
     */
    public function listBook()
    {
        $merchant_id = session('merchant.merchant_id');
        $page = input('param.page/n', 1);
        $pagesize = (int)input('param.DataTables_Table_0_length',20);
        $type = input('param.type') ? input('param.type') : 0;
        $booklist = $this->book->getBookList($merchant_id,$pagesize, $type);
        $this->assign([
            'data' => $booklist,
            'type' => $type,
            'pagesizes' => $pagesize,
            'page'=>$page,
            'point'=>input('param.point', 0),
            'keyword'=>input('param.keyword', ''),
            'begintime'=>input('param.begintime', ''),
            'endtime'=>input('param.endtime', '')
        ]);
        return view('listBook');
    }

    /**
     * 添加图书
    */
    public function createBook()
    {
        $id = input("bid/n",0);
        $categorylist = $this->book->getCategoryList();
        // 归还地址
        $return_place = GoodsModel::getReturnPlace();
	$book_class = $this->book->getBookClass();
        $book_type = $this->book->getBookType();
        $book_category = [];
        $merchant = session('merchant.merchant_id');
        if($id > 0){
            $book_info = $this->book->getBookInfo($id);
            $book_info['img_main'] = empty($book_info['img_main']) ? $book_info['img_main'] : explode(",",$book_info['img_main']);
            $book_info['revert_id'] = explode(",",$book_info['revert_id']);
            $book_info['revert_all'] = count($book_info['revert_id']) == count($return_place) ? 1 : 0 ;
            $book_info['max_advance_days'] = intval($book_info['max_advance_days'])/30;
            $book_info['medium_num'] = empty($book_info['img_medium']) ? 0 : 1 ;
            $book_info['main_num'] = empty($book_info['img_main']) ? 0 : count($book_info['img_main']) ;
            $book_info['stock'] = $book_info['stock'] == 0 ? '' : $book_info['stock'];
            $book_category = $this->book->getBookCategoryList($id);
            $is_show_min = 1;
        }else{
            $book_info = $this->initData();
            $book_info['max_advance_days'] = intval($book_info['max_advance_days'])/30;
            $is_show_min = 0;
        }
        $this->assign([
            'return_place'=>$return_place,
            'category'=>$categorylist,
            'book_info'=>$book_info,
            'merchant'=>$merchant,
            'book_category'=>$book_category,
            'is_show_min'=>$is_show_min,
	    'book_class'=>$book_class,
            'book_type'=>$book_type,
        ]);
        return view('createBook');
    }

    /**
     * 修改图书
     */
    public function updateBook()
    {
        $book_id = input('bookid/n',0);
        $page = input('param.page/n', 1);
        $type = input('param.type/n', 0);
	$book_class = $this->book->getBookClass();
        $book_type = $this->book->getBookType();
        $book_info = $this->book->getBookInfo($book_id);
        $book_info['img_main'] = empty($book_info['img_main']) ? $book_info['img_main'] : explode(",",$book_info['img_main']);
        $book_info['revert_id'] = explode(",",$book_info['revert_id']);
        $book_category = $this->book->getBookCategoryList($book_id);
        $categorylist = $this->book->getCategoryList();
        $book_info['max_advance_days'] = intval($book_info['max_advance_days'])/30;
        // 归还地址
        $return_place = GoodsModel::getReturnPlace();
        $book_info['revert_all'] = count($book_info['revert_id']) == count($return_place) ? 1 : 0 ;
        $book_info['medium_num'] = empty($book_info['img_medium']) ? 0 : 1 ;
        $book_info['main_num'] = empty($book_info['img_main']) ? 0 : count($book_info['img_main']) ;
        $book_info['stock'] = $book_info['stock'] == 0 ? '' : $book_info['stock'];
        $this->assign([
            'book_info'=>$book_info,
            'book_category'=>$book_category,
            'return_place'=>$return_place,
            'category'=>$categorylist,
            'page'=>$page,
            'type'=>$type,
            'keyword'=>input('param.keyword', ''),
            'begintime'=>input('param.begintime', ''),
            'endtime'=>input('param.endtime', ''),
            'book_class'=>$book_class,
            'book_type'=>$book_type
        ]);
        return view('updateBook');
    }

    /**
     * 复制系列图书
     */
    public function copyBook()
    {
        $book_id = input('copyid/n',0);
        $page = input('param.page/n', 1);
        $type = input('param.type/n', 0);
        $book_info = $this->book->getBookInfo($book_id);
        $book_info['img_main'] = empty($book_info['img_main']) ? $book_info['img_main'] : explode(",",$book_info['img_main']);
        $book_info['revert_id'] = explode(",",$book_info['revert_id']);
        $book_category = $this->book->getBookCategoryList($book_id);
        $categorylist = $this->book->getCategoryList();
        $book_info['max_advance_days'] = intval($book_info['max_advance_days'])/30;
        // 归还地址
        $return_place = GoodsModel::getReturnPlace();
        $book_info['revert_all'] = count($book_info['revert_id']) == count($return_place) ? 1 : 0 ;
        $book_info['stock'] = $book_info['stock'] == 0 ? '' : $book_info['stock'];
        $book_info['medium_num'] = 0 ;
        $book_info['main_num'] = 0 ;
        $book_info['summary']='';
        $this->assign([
            'book_info'=>$book_info,
            'book_category'=>$book_category,
            'return_place'=>$return_place,
            'category'=>$categorylist,
            'page'=>$page,
            'type'=>$type,
            'keyword'=>input('param.keyword', ''),
            'begintime'=>input('param.begintime', ''),
            'endtime'=>input('param.endtime', '')
        ]);
        return view('copyBook');
    }

    /**
     * 修改图书信息
     */
    public function updateBookInfo()
    {
        if(Request::instance()->method() == 'POST'){
            $req_data = Request::instance()->param();
            $bookid = $req_data['id'];
            $req_data['status'] = $req_data['type'];
            if(strpos($req_data['file_cover'][0],"http") === false){
                $req_data['img_medium'] = config('oss_imgRootPath').'book/cover/'.$req_data['file_cover'][0];//."@!book_cover";
            }else{
                $req_data['img_medium'] = $req_data['file_cover'][0];
            }
            if(!empty($req_data['book_details_images'])){
                $details_images = explode(",",$req_data['book_details_images']);
                foreach ($details_images as $k => $dimg){
                    if(strpos($dimg,"http") === false){
                        $details_images[$k] = config('oss_imgRootPath').'book/details/'.$dimg;//."@!goods_detail";
                    }else{
                        $details_images[$k] = $dimg;
                    }
                }
                $req_data['img_main'] = implode(",",$details_images);
            }else{
                $req_data['img_main'] = "";
            }
            $req_data['max_advance_days'] = intval($req_data['max_advance_days'])*30;
            $category = $req_data['category-tag'];
            $req_data['revert_id'] = implode(",",$req_data['revert_id']);
            if($req_data['status'] == 2){
                $req_data['shelf_time'] = time();
            }
            unset($req_data['type'],$req_data['id'],$req_data['__token__'],$req_data['file_cover'],$req_data['book_details_images'],$req_data['category-tag']);
            $result = $this->book->updateBookInfo($bookid,$req_data);
            if($result !== false){
                $res = $this->book->bindBookCategoryTag($bookid,$category);
            }else{
                $res = false;
            }
            if($res !== false){
                echo json_encode(array('status'=>1,'msg'=>"图书添加成功",'data'=>$res));
            }else{
                echo json_encode(array('status'=>0,'msg'=>"图书添加失败，请稍后再试"));
            }
            exit();
        }
    }

    public function initData(){
        $data = [
            'id'=>0,
            'title'=>'',
            'subtitle'=>'',
            'level_num'=>'',
            'pub_date'=>'',
            'origin_title'=>'',
            'binding'=>'',
            'author'=>'',
            'translator'=>'',
            'pages'=>'',
            'img_medium'=>'',
            'img_main'=>'',
            'publisher'=>'',
            'isbn10'=>'',
            'isbn13'=>'',
            'summary'=>'',
            'price'=>'',
            'discount'=>100,
            'stock'=>'',
            'revert_id'=>'',
            'least_advance_days'=>4,
            'max_advance_days'=>90,
            'series'=>'',
            'shelf_mark'=>'',
            'min_age'=>0,
            'max_age'=>0,
            'language'=>0,
            'main_num'=>0,
            'status'=>0,
            'medium_num'=>0
        ];
        return $data;
    }

    /**
     * 添加图书信息
    */
    public function addBookInfo()
    {
        if(Request::instance()->method() == 'POST'){
            $req_data = Request::instance()->param();
            $merchant_id = session('merchant.merchant_id');
            $storeinfo = $this->book->getStoreInfo($merchant_id);
            $req_data['status'] = $req_data['type'];
            if(strpos($req_data['file_cover'][0],"http") === false){
                $req_data['img_medium'] = config('oss_imgRootPath').'book/cover/'.$req_data['file_cover'][0];//."@!book_cover";
            }else{
                $req_data['img_medium'] = $req_data['file_cover'][0];
            }
            if(!empty($req_data['book_details_images'])){
                $details_images = explode(",",$req_data['book_details_images']);
                foreach ($details_images as $k => $dimg){
                    if(strpos($dimg,"http") === false){
                        $details_images[$k] = config('oss_imgRootPath').'book/details/'.$dimg;//."@!goods_detail";
                    }else{
                        $details_images[$k] = $dimg;
                    }
                }
                $req_data['img_main'] = implode(",",$details_images);
            }else{
                $req_data['img_main'] = "";
            }
            $category = $req_data['category-tag'];
            $req_data['store_id'] = $storeinfo['store_id'];
            $req_data['merchant_id'] = $merchant_id;
            $req_data['revert_id'] = implode(",",$req_data['revert_id']);
            if($req_data['status'] == 2){
                $req_data['shelf_time'] = time();
            }
            $req_data['surplus_stock'] = $req_data['stock'];
            $req_data['max_advance_days'] = intval($req_data['max_advance_days'])*30;
            unset($req_data['type'],$req_data['__token__'],$req_data['file_cover'],$req_data['book_details_images'],$req_data['category-tag']);
            if(isset($req_data['id'])){
                unset($req_data['id']);
            }
            $bookid = $this->book->addBookInfo($req_data);
            if($bookid !== false){
                $res = $this->book->bindBookCategoryTag($bookid,$category);
            }else{
                $res = false;
            }
            if($res !== false){
                echo json_encode(array('status'=>1,'msg'=>"图书添加成功",'data'=>$res));
            }else{
                echo json_encode(array('status'=>0,'msg'=>"图书添加失败，请稍后再试"));
            }
            exit();
        }
    }

    /**
     * 获取系列数据，更新当前数据
     */
    public function getSeriesData()
    {
        if(Request::instance()->method() == 'POST') {
            $book_id = input('id/n',0);
            $res = $this->book->getSeriesData($book_id);
            if ($res !== false){
                return returnJson(1, '获取数据成功');
            }else{
                return returnJson(0, '获取数据失败,请稍后再试！');
            }
        }
    }

    /**
     * 删除图书
    */
    public function deleteBook()
    {
        if(Request::instance()->method() == 'POST') {
            $book_id = input('bookid/n',0);
            $res = $this->book->delBook($book_id);
            if ($res !== false){
                return returnJson(1, '删除成功');
            }else{
                return returnJson(0, '删除失败');
            }
        }
    }

    /**
     * 图书下架
    */
    public function bookPutDown()
    {
        if(Request::instance()->method() == 'POST') {
            $book_id = input('bookid/n',0);
            $res = $this->book->downBook($book_id);
            if (request()->isAjax() && $res !== false) {
                return returnJson(1, "下架成功");
            }
        }
    }

    /**
     * 图书上架
     */
    public function bookPutOn()
    {
        if(Request::instance()->method() == 'POST') {
            $book_id = input('bookid/n',0);
            $res = $this->book->onBook($book_id);
            if (request()->isAjax() && $res !== false) {
                return returnJson(1, "上架成功");
            }else{
                return returnJson(0, "上架失败，请先上传封面图片");
            }
        }
    }

    /**
     * 上传图书相关图片
     */
    public function uploadImg()
    {
        $type = input('type/n', 0);  //1-图书封面(小) 2-图书详情

        if ($type == 1) {
            $imgPath = config('oss_img_path') . 'book/cover';
            $imgRoot = config('oss_imgRootPath') . 'book/cover/';
        } elseif ($type == 2) {
            $imgPath = config('oss_img_path') . 'book/details';
            $imgRoot = config('oss_imgRootPath') . 'book/details/';
        }else {
            return returnJson(0, '图片类型获取失败', '');
        }
        $imgName = input('name');
        if (empty($imgName)) {
            return returnJson(0, '图片名称获取失败', '');
        }
        $imgUrl = $imgName;
        $oss = new OSSUtils();
        $res = $oss->uploadFile($imgPath."/".$imgName,$_FILES['file']['tmp_name']);
        $res = json_decode($res,true);
        if($res['status'] == 1){
            return returnJson(1, '上传成功', ['imgUrl' => $imgUrl, 'imgPath' => $imgRoot]);
        }else{
            return returnJson(0, $res['msg'], ['imgUrl' => $imgUrl, 'imgPath' => $imgRoot]);
        }
    }

    /** ------------------------------------------------------------------图书处理(上)--------------------------------------------------------------------- **/
    /** ------------------------------------------------------------------图书订单(下)--------------------------------------------------------------------- **/

    /*
     * 图书订单首页列表
    */
    public function borrowOrder()
    {
        if(!input('?get.type') || input('get.type') == null){
            $order_status = 1;
        }else{
            $order_status = input('get.type');
        }
        switch($order_status){
            //全部
            case 1:
                $where['bo.status']    = ['not in', [9,10]];
                break;
            //待发货
            case 2:
                $where['bo.status']    = ['in', [2]];
                break;
            //待归还
            case 3:
                $where['bo.status']    = ['in',[3,4]];
                $where['bo.rent_end_time']    = ['egt',time()];
                break;
            //待结算
            case 4:
                $where['bo.status']    = ['in', [5]];
                break;
            //成功订单
            case 5:
                $where['bo.status']    = ['in', [7,8,-1]];
                break;
            //逾期订单
            case 6:
                $where['bo.status']    = ['in',[3,4]];
                $where['bo.rent_end_time']    = ['lt',time()];
                break;
            //取消订单
            case 7:
                $where['bo.status']    = ['in',[9,10,11,12]];
                //$where['bo.pay_type']    = ['gt',0];
                //$where['bo.pay_amount']    = ['gt',0];
                break;
        }
        $where['bo.merchant_id'] = ['eq', session('merchant.merchant_id')];
        $where['bo.origin_id'] = ['eq', 0];
        $page_number = 20;
        $keyword = input("keyword/s",'');
        $keyword_end = input("keyword_end/s",'');
	$data['order_list'] = $this->book->getBorrowOrderList($page_number,$where);
        $data['page'] = $data['order_list']->render();
        $data['page_list'] = $data['order_list']->total();
        $data['page_number'] = count($data['order_list']);
        $data['type'] = input('type');
        $data['year']=date('Y');
        $data['month']=date('m');
        return view('borrowOrder', ['data' => $data,'keyword'=>$keyword,'keyword_end'=>$keyword_end,'type'=>$order_status]);
    }

    /*
     * 图书订单发货处理
    */
    public function borrowDeliver()
    {
        $order_id = input("order_id/n",0);
        $deliver_orderinfo = $this->book->getDeliverOrderInfo($order_id);
        $this->assign([
            'deliver_orderinfo'=>$deliver_orderinfo,
        ]);
        return view('borrowDeliver');
    }

    /*
     * 添加图书订单发货信息
    */
    public function deliverAdd()
    {
        if(Request::instance()->method() == 'POST') {
            $req_data = Request::instance()->param();
            $res = $this->book->saveDeliverInfo($req_data);
            if ($res !== false) {
                return returnJson(1, "发货成功");
            }else{
                return returnJson(0, "发货失败，请稍后再试");
            }
        }
    }

    public function deliverSave()
    {
        if(Request::instance()->method() == 'POST') {
            $req_data = Request::instance()->param();
            $res = $this->book->saveDeliverStatus($req_data);
            if ($res !== false) {
                return returnJson(1, "发货成功");
            }else{
                return returnJson(0, "发货失败，请稍后再试");
            }
        }
    }

    /*
     * 图书订单结算
    */
    public function borrowJiesuan()
    {
        $order_id = input("order_id/n",0);
        $jiesuan_orderinfo = $this->book->getJiesuanOrderInfo($order_id);
        $this->assign([
            'jiesuan_orderinfo'=>$jiesuan_orderinfo,
        ]);
        return view('borrowJiesuan');
    }

    /*
     * 图书订单结算处理
    */
    public function jiesuanHandle()
    {
        if(Request::instance()->method() == 'POST') {
            $req_data = Request::instance()->param();
            $res = $this->book->handleJiesuanInfo($req_data);
            if ($res !== false) {
                return returnJson(1, "结算成功");
            }else{
                return returnJson(0, "结算失败，请稍后再试");
            }
        }
    }

    /*
     * 图书订单详情
    */
    public function borrowDetail()
    {
        $order_id = input("order_id/n",0);
        $order_detail = $this->book->getBorrowOrderDetail($order_id);
        $ship_count_down = (time()-$order_detail['order_shipping_time']) < 86400 ? (86400-(time()-$order_detail['order_shipping_time'])) : 0 ;
        $order_detail['ship_count_down'] = $ship_count_down;
        $order_detail['return_deliver_company'] = "顺丰快递";
        $order_detail['return_logistics_name'] = "shunfeng";
        $order_detail['return_back_address'] ="博鸟绘本 18301119746 浙江省杭州市余杭区五常街道高教路970号梦想E商村一号楼";
        $this->assign([
            'order_detail'=>$order_detail,
        ]);
        return view('borrowDetail');
    }

    /**
     * 修改物流公司
     */
    public function editShipCompany(){
        if(Request::instance()->method() == 'POST'){
            if (!session('merchant')) {
                echo json_encode(array('status'=>0,'msg'=>"未登录"));
                exit();
            }
            $company_name = trim(input("name/s",""));
            $company_code = trim(input("code/s",""));
            $order_id = input("order_id/n",0);
            if($order_id == 0){
                echo json_encode(array('status'=>0,'msg'=>"订单号有误，物流公司保存失败"));
                exit();
            }
            $res = $this->book->editShipCompany($order_id,$company_name,$company_code);
            if($res !== false){
                echo json_encode(array('status'=>1,'msg'=>"物流公司保存成功","data"=>['code'=>$company_code,'name'=>$company_name]));
            }else{
                echo json_encode(array('status'=>0,'msg'=>"物流公司保存失败"));
            }
            exit();
        }
    }

    /**
     * 修改物流单号
     */
    public function editShipExpressid(){
        if(Request::instance()->method() == 'POST'){
            if (!session('merchant')) {
                echo json_encode(array('status'=>0,'msg'=>"未登录"));
                exit();
            }
            $expressid = trim(input("eid/s",""));
            $order_id = input("order_id/n",0);
            if($order_id == 0){
                echo json_encode(array('status'=>0,'msg'=>"订单号有误，物流单号保存失败"));
                exit();
            }
            $res = $this->book->editShipExpressid($order_id,$expressid);
            if($res !== false){
                echo json_encode(array('status'=>1,'msg'=>"物流单号保存成功","data"=>['eid'=>$expressid]));
            }else{
                echo json_encode(array('status'=>0,'msg'=>"物流单号保存失败"));
            }
            exit();
        }
    }

    /**
     * 获取物流信息
     */
    public function getOrderLogistics(){
        if(Request::instance()->method() == 'POST') {
            $company_code = trim(input('company/s', ''));
            $logistics_num = trim(input('code/s', ''));
            if (empty($company_code) || empty($logistics_num)) {
                echo json_encode(array('status' => 0, 'msg' => "请传递完整物流信息"));
                exit();
            }
            // $result = $this->logistics($company_code, $logistics_num);

            switch ($company_code){
                case 'shunfeng':
                    $bsp = new BSP();
                    $data = $bsp->orderRoute($logistics_num);
                    if ($data['status']==0) {
                        echo json_encode(array('status' => 0, 'msg' => "无物流信息，请联系商家！"));
                    } else {
                        echo json_encode(array('status' => 1, 'msg' => "查询成功", 'data' => $data));
                    }
                    break;
                case 'jd':
                    include_once ROOT_PATH . 'extend/jos-open-api-sdk-2.0/Jd.php';
                    $js = new \Jd();
                    $data = $js->search($logistics_num,true);
                    if(is_array($data)){
                        $jd_result = $this->jd_arr_check($data);
                        echo json_encode(array('status' => 1, 'msg' => "查询成功", 'data' => $jd_result));
                    }else{
                        echo json_encode(array('status' => 0, 'msg' => "查询失败"));
                    }
                    break;
                default:
                    $result = $this->logistics($company_code, $logistics_num);
                    $data = json_decode($result, true);
                    if (!$data['showapi_res_body']['flag']) {
                        echo json_encode(array('status' => 0, 'msg' => "无物流信息，请联系商家！"));
                    } else {
                        echo json_encode(array('status' => 1, 'msg' => "查询成功", 'data' => $data['showapi_res_body']['data']));
                    }
                    break;
            }
            exit();
        }else{
            echo json_encode(array('status' => 0, 'msg' => "请求方式错误,应为post"));
            exit();
        }
    }
    public function jd_arr_check($arr) {
        $result = array();
        foreach ($arr as $key => $val) {
            # code...
            $result[$key] = ['context' => $val['opeTitle'] , 'time' => $val['opeTime']];
        }
        return $result;
    }
	public function arr_check($arr){
        if(is_array($arr)) {
            if(isset($arr[0])) {
                $data = array();
                foreach ($arr as $key => $val) {
                    if(empty($data)) {
                        $data = $this->arr_check($val);
                    }
                    else {
                        if(!isset($data[0])){
                            $abc = $data;
                            unset($data);
                            $data[0] = $abc;
                        }
                        array_push($data, $this->arr_check($val)) ;
                    }
                }
                return $data;
            }else {
                return $arr;
            }
        }
    }
    public function getPushRoute(){
        if(Request::instance()->method() == 'POST') {
            $company_code = trim(input('company/s', ''));
            $logistics_num = trim(input('code/s', ''));
            if (empty($company_code) || empty($logistics_num)) {
                echo json_encode(array('status' => 0, 'msg' => "请传递完整物流信息"));
                exit();
            }
            // $result = $this->logistics($company_code, $logistics_num);

            $rout_list = Db('zj_express_order')->where('express_no',$logistics_num)->where('type',$company_code)->find();

            $data = array();

            switch ($company_code){
                case 'shunfeng':
                    $chuli = unserialize($rout_list['push_route']);
                    $chuli = $this->arr_check($chuli);
                    if(isset($chuli['remark'])) {
                        $data[] = ['context' => $chuli['remark'] , 'time' => $chuli['acceptTime']];
                    }else {
                        foreach ($chuli as $key => $val) {
                            # code...
                            $data[] = ['context' => $val['remark'] , 'time' => $val['acceptTime']];
                        }
                    }
                    if (empty($data)) {
                        echo json_encode(array('status' => 0, 'msg' => "无物流信息，请联系商家！"));
                    } else {
                        echo json_encode(array('status' => 1, 'msg' => "查询成功", 'data' => $data));
                    }
                    break;
                case 'jd':
                    include_once ROOT_PATH . 'extend/jos-open-api-sdk-2.0/Jd.php';
                    $js = new \Jd();
                    $data = $js->search($logistics_num);
                    if(is_array($data)){
                        echo json_encode(array('status' => 1, 'msg' => "查询成功", 'data' => $data));
                    }else{
                        echo json_encode(array('status' => 0, 'msg' => "查询失败"));
                    }
                    break;
                default:
                    $result = $this->logistics($company_code, $logistics_num);
                    $data = json_decode($result, true);
                    if (!$data['showapi_res_body']['flag']) {
                        echo json_encode(array('status' => 0, 'msg' => "无物流信息，请联系商家！"));
                    } else {
                        echo json_encode(array('status' => 1, 'msg' => "查询成功", 'data' => $data['showapi_res_body']['data']));
                    }
                    break;
            }
            exit();
        }else{
            echo json_encode(array('status' => 0, 'msg' => "请求方式错误,应为post"));
            exit();
        }
    }
    /**
     * 获取图书订单图书详情
    */
    public function getDeliverOrderBookList(){
        $start_time = strtotime(date("Y-m-d")." 00:00:00");
        $end_time = strtotime(date("Y-m-d")." 23:59:59")+86400*5;
        //$deliver_order = Db('zj_book_order')->field("id,order_sn")->where("status = 2 and rent_start_time <= $end_time")->select();
        $deliver_order_id = Db('zj_book_order')->where("status = 2 and rent_start_time <= $end_time and origin_id = 0")->value('group_concat(id)');
        if(!empty($deliver_order_id)){
            $book_list = Db('zj_book')->alias('zb')
                ->join('zj_book_order_list zbol','zb.id = zbol.book_id','left')
                ->field("zbol.order_id,zb.title,zb.publisher,zb.isbn13 as isbn")
                ->where("zbol.order_id in ($deliver_order_id)")
                ->order("zb.creater asc,convert(zb.publisher USING gbk) COLLATE gbk_chinese_ci")
                ->select();
            foreach ($book_list as $k => $v){
                $order_info = Db('zj_book_order')->alias('bo')
                    ->field("order_sn,from_unixtime(rent_start_time,'%Y-%m-%d') as rent_start_time,from_unixtime(rent_end_time,'%Y-%m-%d') as rent_end_time,address")
                    ->where("id = {$v['order_id']}")->find();
                $book_list[$k]['order_sn'] = $order_info['order_sn'];
                $book_list[$k]['rent_start_time'] = $order_info['rent_start_time'];
                $book_list[$k]['rent_end_time'] = $order_info['rent_end_time'];
                $address_info = json_decode($order_info['address'],true);
                $book_list[$k]['user_phone'] = $address_info['mobile'];
                $book_list[$k]['user_name'] = $address_info['address_name'];
            }
            echo json_encode(array('status' => 1, 'msg' => "数据获取成功",'data'=>$book_list));
        }else{
            echo json_encode(array('status' => 0, 'msg' => "今天暂无发货订单"));
        }
        exit();
    }

    /**
     * 获取单笔订单图书详情
     */
    public function getDeliverOrderTicket(){
        $order = input("order/n",0);
        if(!empty($order)){
            $book_list = Db('zj_book')->alias('zb')
                ->join('zj_book_order_list zbol','zb.id = zbol.book_id','left')
                ->field("zbol.order_id,zb.title,zb.publisher,zb.isbn13 as isbn")
                ->where("zbol.order_id in ($order)")
                ->order("zb.creater asc,convert(zb.publisher USING gbk) COLLATE gbk_chinese_ci")
                ->select();
            $order_info = Db('zj_book_order')
                ->field("order_sn,from_unixtime(rent_start_time,'%Y-%m-%d') as rent_start_time,from_unixtime(rent_end_time,'%Y-%m-%d') as rent_end_time,address")
                ->where("id = {$book_list[0]['order_id']}")->find();
            $address_info = json_decode($order_info['address'],true);
            $order_info['name'] = $address_info['address_name'];
            $order_info['mobile'] = $address_info['mobile'];
//            foreach ($book_list as $k => $v){
//                $order_info = Db('zj_book_order')->alias('bo')
//                    ->join('user u','bo.user_id = u.user_id','left')
//                    ->join('identi id','bo.user_id = id.user_id','left')
//                    ->field("bo.order_sn,from_unixtime(bo.rent_start_time,'%Y-%m-%d') as rent_start_time,from_unixtime(bo.rent_end_time,'%Y-%m-%d') as rent_end_time,u.user_phone,id.identi_real_name")
//                    ->where("id = {$v['order_id']}")->find();
//                $book_list[$k]['order_sn'] = $order_info['order_sn'];
//                $book_list[$k]['rent_start_time'] = $order_info['rent_start_time'];
//                $book_list[$k]['rent_end_time'] = $order_info['rent_end_time'];
//                $book_list[$k]['user_phone'] = $order_info['user_phone'];
//                $book_list[$k]['identi_real_name'] = $order_info['identi_real_name'];
//            }
            echo json_encode(array('status' => 1, 'msg' => "数据获取成功",'data'=>['book_list'=>$book_list,'order_info'=>$order_info]));
        }else{
            echo json_encode(array('status' => 0, 'msg' => "订单无效"));
        }
        exit();
    }

    public function pbatchDeliverOrderTicket(){
        $end_time = strtotime(date("Y-m-d")." 23:59:59")+86400*5;
        $order = Db('zj_book_order')->field("id")
            ->where("status = 2 and rent_start_time <= $end_time and origin_id = 0")
            ->order("rent_start_time asc,id asc")
            ->select();
        if(!empty($order)){
            $data = [];
            foreach ($order as $k => $v){
                $book_list = Db('zj_book')->alias('zb')
                    ->join('zj_book_order_list zbol','zb.id = zbol.book_id','left')
                    ->field("zbol.order_id,zb.title,zb.publisher,zb.isbn13 as isbn")
                    ->where("zbol.order_id in ({$v['id']})")
                    ->order("zb.creater asc,convert(zb.publisher USING gbk) COLLATE gbk_chinese_ci")
                    ->select();
                $order_info = Db('zj_book_order')
                    ->field("order_sn,from_unixtime(rent_start_time,'%Y-%m-%d') as rent_start_time,from_unixtime(rent_end_time,'%Y-%m-%d') as rent_end_time,address")
                    ->where("id = {$book_list[0]['order_id']}")->find();
                $address_info = json_decode($order_info['address'],true);
                $order_info['name'] = $address_info['address_name'];
                $order_info['mobile'] = $address_info['mobile'];
                $data[$k]['book_list'] = $book_list;
                $data[$k]['order_info'] = $order_info;
            }
            echo json_encode(array('status' => 1, 'msg' => "数据获取成功",'data'=>$data));
        }else{
            echo json_encode(array('status' => 0, 'msg' => "订单无效"));
        }
        exit();
    }

    /**
     * 获取图书订单图书详情
     */
    public function setOrderRemark(){
        $remark = input('remark/s','');
        $order_id = input('order/n',0);
        if($order_id == 0){
            echo json_encode(array('status' => 0, 'msg' => "备注设置失败"));
            exit();
        }
        $res = Db('zj_book_order')->where("id = $order_id")->update(['remark'=>$remark]);
        if($res !== false){
            echo json_encode(array('status' => 1, 'msg' => "备注设置成功"));
        }else{
            echo json_encode(array('status' => 0, 'msg' => "备注设置失败"));
        }
        exit();
    }

    public function getBookRentItem(){
        $book_id = input("book_id/n",0);
        $rent_list = Db("zj_book")->alias("b")
            ->join("zj_book_order_list bol","b.id=bol.book_id","left")
            ->join("zj_book_order bo","bo.id = bol.order_id","left")
            ->join("user u","u.user_id = bo.user_id","left")
            ->field("u.user_phone,bo.order_sn,bo.id,bo.status,bo.address,bo.book_num,
            FROM_UNIXTIME(rent_start_time,'%Y-%m-%d') as start_time,
            FROM_UNIXTIME(rent_end_time,'%Y-%m-%d') as end_time")
            ->where("b.id = $book_id and bo.status in (1,2,3,4,5,6) and origin_id = 0")
            ->select();
        $stock_info = Db("zj_book")->where("id = $book_id")->field("stock,surplus_stock")->find();
        $status = '';
        foreach ($rent_list as $k => $v){
            $address = json_decode($v['address'],true);
            $rent_list[$k]['mobile'] = $address['mobile'];
            $rent_list[$k]['name'] = $address['address_name'];
            unset($rent_list[$k]['address']);
            switch ($v['status']){
                case 1 :
                    $status = "待支付";
                    break;
                case 2 :
                    $status = "待发货";
                    break;
                case 3 :
                    $status = "待确认收货";
                    break;
                case 4 :
                    $status = "待归还";
                    break;
                case 4 :
                    $status = "待归还";
                    break;
                case 5 :
                    $status = "待结算";
                    break;
                case 6 :
                    $status = "待确认结算";
                    break;
                default:
                    break;
            }
            $rent_list[$k]['status'] = $status;
        }
        if($rent_list !== false){
            echo json_encode(['status'=>1,"msg"=>"图书租赁清单查询成功",'data'=>['rent_list'=>$rent_list,'stock_info'=>$stock_info]]);
        }else{
            echo json_encode(['status'=>0,"msg"=>"图书租赁清单查询失败"]);
        }
        exit();
    }

    public function getLoseRate(){
        $exist_count = Db("zj_book")->where("surplus_stock != 0 and status = 2")->value("count(*)");
        $lose_count = Db("zj_book")->where("surplus_stock = 0 and status = 2")->value("count(*)");
        $total_count = Db("zj_book")->where("status = 2")->value("count(*)");
        $rate = sprintf("%.2f",$lose_count/$total_count*100);
        $exist_rate = sprintf("%.2f",$exist_count/$total_count*100);
        $total_rate = sprintf("%.2f",$rate+$exist_rate);
        echo json_encode(['status'=>1,"msg"=>"缺货率获取成功","lose_rate"=>$rate,"exist_rate"=>$exist_rate,"total_rate"=>$total_rate]);
        exit();
    }

    /**
     * 图片处理，下载原图并上传oss,替换URL
    */
    public function changeImage(){
        set_time_limit(0);
        $path = "/home/www-data/zujiekeji/s.zujiekeji.cn/book-image/";
        $bimage_list = Db("zj_book")->field("id,img_medium")->where("img_medium not like '%oss.zujiekeji.cn%'")->select();

        foreach ($bimage_list as $k => $v){
            if(empty($v['img_medium'])){
                continue;
            }
            $url = $v['img_medium'];
            $filename = pathinfo($url, PATHINFO_BASENAME);
            $in = fopen($url, "rb");
            $out = fopen($path.$filename, "wb");
            while($chunk = fread($in,8192))
            {
                fwrite($out, $chunk, 8192);
            }
            fclose($in);
            fclose($out);

            $imgPath = config('oss_img_path') . 'book/cover';
            $imgRoot = config('oss_imgRootPath') . 'book/cover/';

            $oss = new OSSUtils();
            $res = $oss->uploadFile($imgPath."/".$filename,$path.$filename);
            $res = json_decode($res,true);
            if($res['status'] == 1){
                Db("zj_book")->where("id = {$v['id']}")->update(['img_medium'=>$imgRoot.$filename]);
            }
        }
    }

    /**
     * 导入图书
    */
    public function inBook(){
        $id = input('id/n',0);
        if($id == 0){
            print_r("请先传递图书ID");
            exit();
        }
        $file = fopen("./book.txt", "r");
        $book=array();
        $i=0;
        while(!feof($file))
        {
            $book[$i]= fgets($file);
            $i++;
        }
        fclose($file);
        $book=array_filter($book);
        $origin_book = Db("zj_book")->where("id = $id")->find();
        unset($origin_book['id']);
        $insert_book = [];
        foreach ($book as $k => $v){
            $origin_book['title'] = $v;
            $origin_book['create_time'] = time();
            $origin_book['update_time'] = time();
            $insert_book[] = $origin_book;
        }
        $res = Db("zj_book")->insertAll($insert_book);
        if($res !== false){
            print_r("导入成功");
        }
    }

    public function bookToWordpress(){
        set_time_limit(0);
        $mysql_conf = array(
            'host'    => 'rm-uf6arn6384zld4851o.mysql.rds.aliyuncs.com',
            'db'      => 'huiben_iboniao',
            'db_user' => 'zujiekeji_2017',
            'db_pwd'  => 'hangzhou_zujiekeji',
        );
        $mysqli = @new \mysqli($mysql_conf['host'], $mysql_conf['db_user'], $mysql_conf['db_pwd']);
        if ($mysqli->connect_errno) {
            die("could not connect to the database:\n" . $mysqli->connect_error);//诊断连接错误
        }
        $mysqli->query("set names 'utf8';");//编码转化
        $select_db = $mysqli->select_db($mysql_conf['db']);
        if (!$select_db) {
            die("could not connect to the db:\n" .  $mysqli->error);
        }
        //var_dump($mysqli);

        $book_list = Db("zj_book")
            ->field("id,title,series,author,img_medium,img_main,publisher,isbn13,summary,price,language")
            ->where("status = 2 and export_status < 1")->select();
        foreach ($book_list as $bk => $bv){
            $language = "";
            switch ($bv['language']){
                case 1:
                    $language = "中文";
                    break;
                case 2:
                    $language = "英文";
                    break;
                case 3:
                    $language = "中英文";
                    break;
                case 4:
                    $language = "中文注音";
                    break;
                default:
                    break;
            }
            $summary = addslashes($bv['summary']);
            $title = addslashes($bv['title']);
            $series = addslashes($bv['series']);
            $publisher = addslashes($bv['publisher']);
            $author = addslashes($bv['author']);
            $aritle = "<div style=\"position: relative;width:100%;\">
                        <div style=\"position: relative;float: left;width:40%;\">
                            <img style=\"width: 100%;\" src=\"{$bv['img_medium']}\" />
                        </div>
                        <div style=\"position: relative;float: left;width:60%;\">
                            <div style=\"margin-top: 80px;margin-left: 20px;\">
                                <span>名称：$title</span><br/>
                                <span>作者：$author</span><br/>
                                <span>出版社：$publisher</span><br/>
                                <span>ISBN：{$bv['isbn13']}</span><br/>
                                <span>单价：￥{$bv['price']}</span><br/>
                                <span>系列：$series</span><br/>
                                <span>语言：$language</span><br/>
                            </div>
                        </div>
                        <div style=\"clear: both;\"></div>
                    </div>
                    <div style=\"width: 95%;line-height: 25px;background-color: #efefef;color: #333333;padding: 10px 20px;\">摘要</div>
                    <div style=\"width: 95%;margin: 20px 0;\">
                        $summary
                    </div>
                    ";
            if(!empty($bv['img_main'])){
                $aritle .= "<div style=\"width: 95%;line-height: 25px;background-color: #efefef;color: #333333;padding: 10px 20px;\">绘本图册</div>";
                $img_main = explode(",",$bv['img_main']);
                foreach ($img_main as $img){
                    $aritle .= "<img style=\"width: 80%; margin: 5px 10%;\" src=\"$img\" />";
                }
            }
            $date=date("Y-m-d H:i:s");
            $name_url = urlencode($bv['title']);
            $guid_search = "select guid from `bn_posts` where guid like '%p=%' order by ID desc limit 1;";
            $guid_info = $mysqli->query($guid_search);
            $gid = 0;
            while ($guid = $guid_info->fetch_assoc()) {
                $gid = explode("p=",$guid['guid'])[1];
            }
            $guid_url="https://huiben.iboniao.com/?p=".(intval($gid)+1);
            $insert_sql = "insert into `bn_posts` (post_author,post_date,post_date_gmt,post_content,post_title,post_name,post_modified,post_modified_gmt,guid) 
            VALUE (1,'$date','$date','$aritle','".$title."','$name_url','$date','$date','$guid_url');";
            $res = $mysqli->query($insert_sql);
            var_dump($res);
            var_dump($insert_sql);
            if($res !== false){
                $aritle_id = $mysqli->insert_id;
                $insert_category_sql = "insert into `bn_term_relationships` (object_id,term_taxonomy_id,term_order) VALUE ($aritle_id,3,0);";
                $category_res = $mysqli->query($insert_category_sql);
                if($category_res !== false){
                    Db("zj_book")->where("id = {$bv['id']}")->update(['export_status'=>1]);
                }
            }
            $guid_info->free();

        }
        $mysqli->close();
    }

    public function getSFMailno(){
        if(Request::instance()->method() == 'POST') {
            $order_id = trim(input('order/s', ''));
            $sfd = new SFDeliver();
            $order = Db('zj_book_order')->alias('bo')
                ->field("bo.address,bo.order_sn,bo.book_num")
                ->where("id = $order_id")
                ->find();
            $address_info = json_decode($order['address'],true);
            $order['user_name'] = $address_info['address_name'];
            $order['province'] = $address_info['province'];
            $order['city'] = $address_info['city'];
            $order['district'] = $address_info['district'];
            $order['address'] = $address_info['address'];
            $order['mobile'] = $address_info['mobile'];
            $res = $sfd->createOrder($order);
            $data = json_decode($res, true);
            if ($data['status'] == 1) {
                echo json_encode(array('status' => 1, 'msg' => "顺丰运单号获取成功！", 'data' => ['mailno'=>$data['data']['mailno']]));
            } else {
                echo json_encode(array('status' => 0, 'msg' => "顺丰运单号获取失败".$data['msg']));
            }
            exit();
        }else{
            echo json_encode(array('status' => 0, 'msg' => "请求方式错误,应为post"));
            exit();
        }
    }

    public function pbatchGetSFMailno(){
        $result = $this->book->pbatchGetSFMailno();
        $deliver_order = $result['deliver_order'];
        $data = $result['data'];
        //$this->exportOrderSFMailInfo($data);
        if(!empty($deliver_order)){
            echo json_encode(array('status' => 1, 'msg' => "顺丰运单号获取成功！", 'data' => ['deliver_order'=>$deliver_order,'export_data'=>$data]));
        }else{
            echo json_encode(array('status' => 0, 'msg' => "今天暂无发货订单"));
        }
        exit();
    }

    public function pbatchImportHandleDeliver(){
        if (!empty($_FILES["SFOrder"]["tmp_name"])) {
            $file_name=$_FILES["SFOrder"]["tmp_name"];
            require_once __DIR__.'/../../../vendor/phpexcel/Classes/PHPExcel.php';
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');//创建读取实例
            $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
            $sheet = $objPHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow();
            $data = [];
            $long_order = '';
            for($i=2;$i<=$highestRow;$i++)
            {
                $tmp['order_sn'] = (string)$objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
                $tmp['mail_no'] = (string)$objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
                $long_order .= $tmp['order_sn'].',';
                $order_id = Db('zj_book_order')->where("order_sn = '{$tmp['order_sn']}' and status = 2")->value("id");
                if(!empty($order_id)){
                    $data[] = [
                        'order_id'=>'',
                        'book_order_id'=>$order_id,
                        'order_express_type'=>1,
                        'order_deliver_company'=>'顺丰快递',
                        'order_deliver_expressid'=>$tmp['mail_no'],
                        'order_logistics_name'=>'shunfeng',
                        'order_since_id'=>0
                    ];
                }
            }
            Db()->startTrans();
            $long_order = trim($long_order,',');
            $total_order_id = Db('zj_book_order')->where("order_sn in ($long_order) and status = 2")->value("group_concat(id)");
            if(!empty($long_order)) {
                $res_status = Db('zj_book_order')->where("order_sn in ($long_order) and status = 2")->update(['status'=>3]);
            }else{
                $res_status = false;
            }
            if(!empty($total_order_id)) {
                $res_deliver_time = Db('goods_order_time')->where("book_order_id in ($total_order_id)")->update(['order_shipping_time'=>time()]);
            }else{
                $res_deliver_time = false;
            }
            if(!empty($data)) {
                $res_deliver = $res = Db("goods_order_deliver")->insertAll($data);
            }else{
                $res_deliver = false;
            }
            if($res_status !== false && $res_deliver_time !== false && $res_deliver !== false){
                Db()->commit();
                $this->success("发货成功",'Book/borrowOrder',[],3);
            }else{
                Db()->rollback();
                $this->error("发货失败,原因：重复发货或者订单号不正确");
            }
        }else{
            $this->error("发货失败,请先选择文件");
        }
        exit();
    }

    public function exportOrderSFMailInfo($data){
        $data = json_decode($data,true);
        require_once __DIR__.'/../../../vendor/phpexcel/Classes/PHPExcel.php';
        $objPHPExcel=new \PHPExcel();

        $letter = ['A','B','C','D','E'];
        //出版社   绘本  收货人   起租日期    手机号码
        $title = ['订单号','收货人','手机','顺丰运单号','错误信息'];
        for($i = 0;$i < count($title);$i++) {
            $objPHPExcel->getActiveSheet()->setCellValue("$letter[$i]1","$title[$i]");
            $objPHPExcel->getActiveSheet()->getColumnDimension($letter[$i])->setWidth('20');
        }
        $datacount=count($data);

        for ($i = 2;$i <= $datacount + 1;$i++)
        {
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value)
            {
                $objPHPExcel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }
        $file_name = date("Y-m-d");
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header("Content-Type:application/octet-stream");
        header('Content-Disposition:attachment;filename="'.$file_name.'顺丰快递信息.xls"');
        header("Content-Transfer-Encoding:binary");

        $write =  \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $write->save('php://output');
    }

    public function pbatchExportSFOrder(){
        $end_time = strtotime(date("Y-m-d")." 23:59:59")+86400*5;
        $deliver_order = Db('zj_book_order')->field("order_sn,id,address,order_sn,book_num")
            ->where("status = 2 and rent_start_time <= $end_time and origin_id = 0")
            ->order("rent_start_time asc,id asc")
            ->select();
        $data = [];
        foreach ($deliver_order as $k => $v){
            $address_info = json_decode($v['address'],true);
            $data[$k]['order_sn'] = $v['order_sn'];
            $data[$k]['company'] = "个人";
            $data[$k]['user'] = $address_info['address_name'];
            $data[$k]['mobile'] = $address_info['mobile'];
            $data[$k]['tel'] = $address_info['mobile'];
            $data[$k]['address'] = $address_info['province'].$address_info['city'].$address_info['district'].$address_info['address'];
            $data[$k]['pay_method'] = "寄付月结";
            $data[$k]['cust_id'] = "5717085362";
            $data[$k]['goods'] = "图书";
            $data[$k]['goods_detail'] = "绘本";
            $data[$k]['goods_count'] = $v['book_num'];
            $data[$k]['mail_count'] = 1;
            $data[$k]['business_type'] = "顺丰特惠";
        }

        require_once __DIR__.'/../../../vendor/phpexcel/Classes/PHPExcel.php';
        $filePath = "/home/www-data/zujiekeji/seller.zujiekeji.cn/public/static/www/merchant/SF_order.xls";
        $objPHPExcel = \PHPExcel_IOFactory::load($filePath);

        $letter = ['A','B','C','D','E','F','G','H','I','J','L','M','P'];
        //订单号   收件公司  联系人   联系电话    手机号码    收件详细地址	付款方式    第三方付月结卡号	托寄物品	托寄物内容	托寄物数量	件数  业务类型
        $datacount=count($data);
        for ($i = 4;$i <= $datacount + 3;$i++)
        {
            $j = 0;
            foreach ($data[$i - 4] as $key=>$value)
            {
                $objPHPExcel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }
        $file_name = date("Y-m-d");
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header("Content-Type:application/octet-stream");
        header('Content-Disposition:attachment;filename="'.$file_name.'.xls"');
        header("Content-Transfer-Encoding:binary");

        $write =  \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $write->save('php://output');
    }

    public function pbatchExportDeliverOrder(){
        $end_time = strtotime(date("Y-m-d")." 23:59:59")+86400*5;
        $deliver_order_id = Db('zj_book_order')->where("status = 2 and rent_start_time <= $end_time and origin_id = 0")->value('group_concat(id)');
        $data = [];
        if(!empty($deliver_order_id)){
            $book_list = Db('zj_book')->alias('zb')
                ->join('zj_book_order_list zbol','zb.id = zbol.book_id','left')
                ->field("zbol.order_id,zb.title,zb.publisher,zb.isbn13 as isbn")
                ->where("zbol.order_id in ($deliver_order_id)")
                ->order("zb.creater asc,convert(zb.publisher USING gbk) COLLATE gbk_chinese_ci")
                ->select();
            foreach ($book_list as $k => $v){
                $order_info = Db('zj_book_order')->alias('bo')
                    ->field("order_sn,from_unixtime(rent_start_time,'%Y-%m-%d') as rent_start_time,from_unixtime(rent_end_time,'%Y-%m-%d') as rent_end_time,address")
                    ->where("id = {$v['order_id']}")->find();
                $data[$k]['publisher'] = $v['publisher'];
                $data[$k]['title'] = $v['title'];
                $address_info = json_decode($order_info['address'],true);
                $data[$k]['user_name'] = $address_info['address_name'];
                $data[$k]['rent_start_time'] = $order_info['rent_start_time'];
                $data[$k]['user_phone'] = $address_info['mobile'];
            }
        }

        require_once __DIR__.'/../../../vendor/phpexcel/Classes/PHPExcel.php';
        $objPHPExcel=new \PHPExcel();

        $letter = ['A','B','C','D','E'];
        //出版社   绘本  收货人   起租日期    手机号码
        $title = ['出版社','绘本','收货人','起租日期','手机号码'];
        for($i = 0;$i < count($title);$i++) {
            $objPHPExcel->getActiveSheet()->setCellValue("$letter[$i]1","$title[$i]");
            $objPHPExcel->getActiveSheet()->getColumnDimension($letter[$i])->setWidth('20');
        }
        $datacount=count($data);
        for ($i = 2;$i <= $datacount + 1;$i++)
        {
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value)
            {
                $objPHPExcel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }
        $file_name = date("Y-m-d");
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header("Content-Type:application/octet-stream");
        header('Content-Disposition:attachment;filename="'.$file_name.'发货单.xls"');
        header("Content-Transfer-Encoding:binary");

        $write =  \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $write->save('php://output');
    }

    public function searchBook(){
        if(Request::instance()->method() == 'POST'){
            $keyword = input("keyword/s");
            $res = Db('zj_book')->field("id,title,img_medium")->where("title like '%$keyword%'")->select();
            if($res !== false){
                echo json_encode(array('status'=>1,'msg'=>"图书添加成功",'data'=>$res));
            }else{
                echo json_encode(array('status'=>0,'msg'=>"图书添加失败，请稍后再试"));
            }
            exit();
        }
    }

    public function changeBook(){
        if(Request::instance()->method() == 'POST'){
            $order = input("order/n");
            $obj_book = input("obj_book/n");
            $change_book = input("change_book/n");
//            var_dump($order);
//            var_dump($obj_book);
//            var_dump($change_book);
            Db()->startTrans();
            $res = Db('zj_book_order_list')->where("order_id = $order and book_id = $change_book")->update(['book_id'=>$obj_book,'update_time'=>time()]);
            $res_stock = Db('zj_book')->where("id = $obj_book")->setDec("surplus_stock");
            $change_res_stock = Db('zj_book')->where("id = $change_book")->setInc("surplus_stock");
            $stock_info = Db('zj_book')->where("id = $obj_book")->field("stock,surplus_stock")->find();
            $change_stock_info = Db('zj_book')->where("id = $change_book")->field("stock,surplus_stock")->find();
            $insert_data = [];
            $insert_data[] = [
                'book_id'=>$obj_book,
                'type'=>4,
                'order_id'=>$order,
                'total_stock'=>$stock_info['stock'],
                'surplus_stock'=>$stock_info['surplus_stock'],
                'merchant_id'=>session('merchant.merchant_id'),
                'stock_sub'=>1,
                'stock_add'=>0,
                'create_time'=>time(),
            ];
            $insert_data[] = [
                'book_id'=>$change_book,
                'type'=>4,
                'order_id'=>$order,
                'total_stock'=>$change_stock_info['stock'],
                'surplus_stock'=>$change_stock_info['surplus_stock'],
                'merchant_id'=>session('merchant.merchant_id'),
                'stock_sub'=>0,
                'stock_add'=>1,
                'create_time'=>time(),
            ];
            $res_histoty = Db('zj_stock_history')->insertAll($insert_data);
            if($res !== false && $res_stock !== false && $res_histoty !== false && $change_res_stock !== false){
                Db()->commit();
                echo json_encode(array('status'=>1,'msg'=>"图书添加成功",'data'=>$res));
            }else{
                Db()->rollback();
                echo json_encode(array('status'=>0,'msg'=>"图书添加失败，请稍后再试"));
            }
            exit();
        }
    }

    public function test(){
        $order = Db('zj_book_order')->alias('bo')
            ->field("bo.address,bo.order_sn,bo.book_num")
            ->where("id = 3293")
            ->find();
        $address_info = json_decode($order['address'],true);
        $order['user_name'] = $address_info['address_name'];
        $order['province'] = $address_info['province'];
        $order['city'] = $address_info['city'];
        $order['district'] = $address_info['district'];
        $order['address'] = $address_info['address'];
        $order['mobile'] = $address_info['mobile'];
        $sfd = new SFDeliver();
        $res = $sfd->searchOrder($order);
        //$res = $sfd->deleteOrder($order);
        $res = $sfd->createOrder($order);
        var_dump($res);
    }

    public function overStock(){
        $data = [
            'book_id'=>input("book"),
            'type'=>5,
            'order_id'=>0,
            'total_stock'=>input("total_stock"),
            'surplus_stock'=>input("surplus_stock"),
            'merchant_id'=>90,
            'stock_add'=>1,
            'stock_sub'=>0,
            'create_time'=>time(),
        ];
        $res = Db('zj_stock_history')->insert($data);
    }

}
